package com.rainbow.support.influxdb.dao;

import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.influxdb.InfluxDB;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.influxdb.impl.InfluxDBResultMapper;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * influxdb持久化
 * @author 傅为地
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class InfluxDao {

    private final InfluxDB influxDB;

    /**
     * 保存单条
     * @param point
     */
    public <T> void save(Point point) {
        log.info("单条录入influxdb参数:{}", JSON.toJSONString(point));
        try {
            influxDB.write(point);
        } catch (Exception e) {
            log.error("单条录入influxdb异常:",e);
        }
    }

    /**
     * 批量保存
     * @param points
     */
    public <T> void saveAll(BatchPoints points) {
        log.info("批量录入influxdb参数:{}", JSON.toJSONString(points));
        try {
            influxDB.write(points);
        } catch (Exception e) {
            log.error("批量录入influxdb异常:",e);
        }
    }

    /**
     * 查询数据
     * @param query
     * @param clas
     * @param <T>
     * @return
     */
    public <T> List<T> select(Query query, Class<?> clas) {
        QueryResult queryResult = influxDB.query(query);
        // thread-safe - can be reused
        InfluxDBResultMapper resultMapper = new InfluxDBResultMapper();
        return (List<T>) resultMapper.toPOJO(queryResult, clas);
    }
}
